
#include "comm/queue.h"
#include "comm/thread.h"

void queue_init(queue_list* q)
{
	q->head = NULL;
	q->tail = NULL;

	mutex_init(&(q->mutex));
}

int enqueue(queue_list* q, void* data)
{
	if ( mutex_trylock(&(q->mutex)) == 0)
	{
		queue_node* pnode = malloc(sizeof(queue_node));
		if(pnode == NULL){
			TRACE("内存空间分配失败！ ");
			exit(1);
		}

		pnode->data = data;
		pnode->next = NULL;

		if(q->tail == NULL)
		{
			// 空队列
			q->head = pnode;
			q->tail = pnode;
		}
		else
		{
			q->tail->next = pnode;
			q->tail = pnode;
		}
	}
	
	mutex_unlock(&(q->mutex));

	return 1;
}

int dequeue(queue_list* q, void** pdata)
{
	int ret = -1;
	queue_node* pnode = NULL;

	if ( mutex_trylock(&(q->mutex)) == 0)
	{
		pnode = q->head;

		if (pnode != NULL)
		{
			*pdata = pnode->data;
			q->head = pnode->next;

			if ( q->head == NULL)
			{
				q->tail = NULL;
			}

			free(pnode);

			ret = 1;
		}
	}
	
	mutex_unlock(&(q->mutex));

	return ret;
}
